import ij.IJ;
import ij.ImagePlus;
import ij.ImageStack;
import ij.hkust.Camera;
import ij.hkust.Constants;
import ij.hkust.gui.laserCtr.LaserCtrChooser;
import ij.hkust.gui.laserCtr.STORM.StormCmdCtr;
import ij.hkust.gui.working.ImgProcessor;
import ij.hkust.gui.working.WorkingWin;
import ij.io.FileSaver;
import ij.plugin.PlugIn;
import ij.plugin.frame.RoiManager;
import ij.process.ByteProcessor;
import ij.process.ImageProcessor;
import ij.process.ShortProcessor;

import java.awt.event.WindowStateListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import mmcorej.CMMCore;

import org.micromanager.MMStudioMainFrame;

public class CameraI implements PlugIn {
	public static CMMCore core = null;

	public static boolean isCanSnap = true;
	ImageProcessor ip;
	Object img;

	ImagePlus imp;

	ImageStack res;

	RoiManager rmanager;
	public static List<Integer> channels = new ArrayList<Integer>();
	public boolean loadCamera() {
		try {
			
			MMStudioMainFrame gui = MMStudioMainFrame.getInstance();
			core = gui.getCore();
			if(gui.isLiveModeOn()){
				gui.enableLiveMode(false);
			}
		} catch (Exception e) {
			IJ.showMessage("error please close the live window before use this software.");
		}
		return true;
	}

	public void run(String arg) {
		int imageCount = Camera.imageCount;
		IJ.register(CameraI.class); // static method of ij/IJ
		// IJ.showMessage("start");
		if (core == null) {
			if(!loadCamera()){
				return;
			}
		}
		try {
			int owidth = (int) core.getImageWidth();
			int oheight = (int) core.getImageHeight();
			Constants.imgWidth = owidth;
			Constants.imgHeight = oheight;
			int index = 0;

			int count = 0;
			while (count < imageCount)
			{
				if(!Constants.isCanStart){
					Thread.currentThread().sleep(500);
					continue;
				}
				ip = null;
				core.snapImage();// Snap
				img = core.getImage();

				count++;

				if (img instanceof byte[]) {
					ip = new ByteProcessor(owidth, oheight);
					ip.setPixels((byte[]) img);
				} else if (img instanceof short[]) {
					ip = new ShortProcessor(owidth, oheight);
					ip.setPixels((short[]) img);
				} else {
					IJ.error("Image Type Error");
					System.exit(-1);
				}
				ImageProcessor ip2 = ip.duplicate();

				ImagePlus imp = new ImagePlus("" + index, ip2);
				FileSaver fs = new FileSaver(imp);
				File file = new File(Camera.savePath);
				if (!file.exists()) {
					file.mkdirs();
				}
				if (Camera.channel > 0) {
					Constants.addRawImage(img, Camera.channel);
					int tmpCount = Constants.getImageCount(Camera.channel);
					fs.saveAsTiff(Camera.savePath+ tmpCount + ".tif");
					WorkingWin.update(Camera.channel, Camera.savePath+ tmpCount + ".tif");
				}
				index++;
			}
		} catch (Exception e) {
			IJ.error(e.getMessage());
			System.exit(-1);
		}

	}
}
